package com.ByteDance.controller;


import com.ByteDance.model.po.FavoriteEntity;
import com.ByteDance.model.po.Relation;
import com.ByteDance.model.po.UserInfos;
import com.ByteDance.model.po.VideoEntity;
import com.ByteDance.model.vo.FeedVO;
import com.ByteDance.model.vo.User;
import com.ByteDance.model.vo.Video;
import com.ByteDance.service.*;
import com.ByteDance.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 视频表
 * </p>
 *
 * @author 朱哥
 * @since 2024-02-25
 */
@Api(tags="视频流Controller")
@Slf4j
@RestController
@RequestMapping("/douyin")
@RequiredArgsConstructor //必备的构造函数，只会对一开始需要初始化的变量去做构造
public class FeedController {
    private final IFavoriteService iFavoriteService;
    private final IRelationService iRelationService;
    private final IUserService iUserService;
    private final IFeedService iFeedService;

    private final Strategy feedStrategy;

    @ApiOperation("视频流接口")
    @GetMapping("/feed")
    public FeedVO feed(@RequestParam(value = "latest_time")String latest_time, HttpServletRequest req){
        if (StringUtils.isEmpty(latest_time)) {
          return FeedVO.fail();
        }

        //获取当前用户id
        int userId = JwtUtils.getUserId(req.getHeader("token"));


        //实现通过latest_time获取视频流---不填则设置为当前时间
        Long latestTime = "0".equals(latest_time)? System.currentTimeMillis():Long.parseLong(latest_time);

        /**
         * 根据参数 - 获取视频的策略和时间戳 来获取视频，方法返回是一个videoList
         */
        Timestamp timestamp = new Timestamp(latestTime);//构造函数 Timestamp(long time)
        List<VideoEntity> videoEntityList = iFeedService.getVideoByStrategy(feedStrategy,timestamp);
        Video[] videos = new Video[videoEntityList.size()];
        /**
         * 用for循环来处理每个视频（查询视频作者信息、视频信息）
         */
        for (int i = 0; i < videoEntityList.size(); i++) {
            VideoEntity videoEntity = videoEntityList.get(i);
            User author = new User();
            //根据视频中的authorId查询author信息
            Integer authorId = videoEntity.getAuthorId();
            author.setUserId(authorId);
            //查询该authorId对应的所有作者信息
            UserInfos userInfos = iUserService.getById(authorId);
            //看看到时候author要不要加个有参构造
            author.setUsername(userInfos.getUsername());
            author.setFollowCount(userInfos.getFollowCount());
            author.setFollowerCount(userInfos.getFollowerCount());
            //查询该userId是否关注了authorId
            boolean flag = true;
            Relation relation = iRelationService.lambdaQuery().eq(Relation::getFollowId, authorId).eq(Relation::getFollowerId, userId).one();
            if(relation == null){
                flag = false;
            }
            author.setFollow(flag);
            author.setAvatar(userInfos.getAvatar());
            author.setBackgroundImage(userInfos.getBackgroundImage());
            author.setSignature(userInfos.getSignature());
            author.setTotalFavorited(userInfos.getTotalFavorited());
            author.setWorkCount(userInfos.getWorkCount());
            author.setFavoriteCount(userInfos.getFavoriteCount());

            videos[i] = new Video(); // 实例化视频对象
            //获取该视频对应的用户id
            videos[i].setAuthor(author);
            int videoId = videoEntity.getVideoId();
            videos[i].setId(videoId);
            videos[i].setPlayurl(videoEntity.getPlayUrl());
            videos[i].setCoverurl(videoEntity.getCoverUrl());
            videos[i].setFavoriteCount(videoEntity.getFavoriteCount());
            videos[i].setCommentCount(videoEntity.getCommentCount());
            boolean flag1 = true;
            FavoriteEntity favoriteEntity = iFavoriteService.lambdaQuery().eq(FavoriteEntity::getUserId, userId)
                    .eq(FavoriteEntity::getVideoId, videoId)
                    .one();
            if(favoriteEntity == null){
                flag1 = false;
            }
            videos[i].setFavorite(flag1);
            videos[i].setTitle(videoEntity.getTitle());
        }

        /**
         * 构建FeedVO返回
         */
        FeedVO feedVO  = FeedVO.success();
        if (videoEntityList.size() > 0) {
            feedVO.setVideoList(videos);
            long publishTime = videoEntityList.get(videoEntityList.size() - 1).getPublishTime().getTime();
            feedVO.setNextTime(publishTime);
            log.info(feedVO.getVideoList()[0].getTitle());//log.infos(String)
        } else {
            //否则设置下次返回七天内的视频，此行仅方便开发测试有用
            feedVO.setNextTime(System.currentTimeMillis()-7*24*60*60*1000);
        }
        log.info("feed:拉取视频成功");
        return feedVO;
    }
}

